import {
  getUsers,
  addUser,
  updUser,
  delUser,
  getDeptList,
  getRolesByDept,
} from '../services/api';

export default {
  namespace: 'users',

  state: {
    // 用户列表数据
    users: {
      list: [],
      pagination: {},
    },
    deptList: [],
    roleList: [],
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(getUsers, payload);
      console.log(response);
      if (response) {
        const { records, total, size, current } = response;
        const users = {
          list: records,
          pagination: {
            total,
            pageSize: size,
            current,
          },
        };
        yield put({
          type: 'save',
          users,
        });
      }
    },
    *add({ payload }, { call, put }) {
      const response = yield call(addUser, payload);
      console.log(response);
      if (response) {
        yield put({
          type: 'fetch',
        });
      }
    },
    *del({ payload }, { call, put }) {
      const response = yield call(delUser, payload);
      console.log(response);
      if (response) {
        yield put({
          type: 'fetch',
        });
      }
    },
    *upd({ payload }, { call, put }) {
      const response = yield call(updUser, payload);
      console.log(response);
      if (response) {
        yield put({
          type: 'fetch',
        });
      }
    },
    *fetchDeptList({ payload }, { call, put }) {
      const response = yield call(getDeptList, payload);
      console.log(response);
      if (response) {
        yield put({
          type: 'saveDeptList',
          deptList: response,
        });
      }
    },
    *fetchRolesByDept({ payload }, { call, put }) {
      const response = yield call(getRolesByDept, payload);
      console.log(response);
      if (response) {
        yield put({
          type: 'saveRoleList',
          roleList: response,
        });
      }
    },
  },

  reducers: {
    save(state, { users }) {
      return {
        ...state,
        users,
      };
    },
    saveDeptList(state, { deptList }) {
      return {
        ...state,
        deptList,
      };
    },
    saveRoleList(state, { roleList }) {
      return {
        ...state,
        roleList,
      };
    },
  },
};
